'use strict'

function isObject(object) {
    return Object.prototype.toString.call(object) === '[object Object]'
}

function getType(target) {
    const template = {
        '[object Array]': 'Array',
        '[object Object]': 'Object',
        '[object Number]': 'Number',
        '[objecct Boolean]': 'Boolean',
        '[object  String]': 'String'
    }
    if (target === null) {
        return null
    }
    if (typeof target === 'object') {
        const type = Object.prototype.toString.call(target)
        return template[type]
    }
    return typeof target
}

function spinnerInit(msg = 'loading...', spinnerAnimation = '|/-\\') {
    const Spinner = require('cli-spinner').Spinner
    const spinner = new Spinner(msg + ' %s')
    spinner.setSpinnerString(spinnerAnimation)
    spinner.start()
    return spinner
}

function sleep(time = 1000) {
    return new Promise(resolve => setTimeout(resolve, time))
}

function exec(command, args, options = {}) {
    const win32 = process.platform === 'win32'
    const cmd = win32 ? 'cmd' : command
    const cmdArgs = win32 ? ['/c'].concat(command, args) : args
    return require('child_process').spawn(cmd, cmdArgs, options)
}

function execAsync(command, args, options) {
    return new Promise((resolve, reject) =>{
        const p = exec(command, args, options)
        p.on('error', reject)
        p.on('exit', resolve)
    })
}

module.exports = {
    isObject,
    getType,
    spinnerInit,
    sleep,
    exec,
    execAsync
}